#include "tranfer.h"

void CTransferServer::_DoConnectEventHandle(int connectfd)
{
	TraceLog("%d", connectfd);

	int serverfd = socket(AF_INET, SOCK_STREAM, 0);
	if(serverfd < 0){
		ErrorLog("socket");
		return;
	}

  TraceLog("the serverfd : %d", serverfd);
  // 1. 连接 socks5 服务器
	if(connect(serverfd, (struct sockaddr*)&_socks5addr, sizeof(_socks5addr)) < 0)
	{
		ErrorLog("connect error");
		close(serverfd);
		return;
	}

  // 2. 建立新连接(两个不同的套接字映射到同一个连接上)
	Connect* connect = new Connect;
	SetNonblocking(connectfd);
	connect->_clientChannel._fd = connectfd;
	connect->_clientChannel._event = EPOLLIN;
	OperateEvent(connectfd, connect->_clientChannel._event, EPOLL_CTL_ADD);
	connect->_counter++;
	_connectMap[connectfd] = connect;

	SetNonblocking(serverfd);
	connect->_serverChannel._fd = serverfd;
	connect->_serverChannel._event = EPOLLIN;
	OperateEvent(serverfd, connect->_serverChannel._event, EPOLL_CTL_ADD);
	connect->_counter++;
	_connectMap[serverfd] = connect;
}

// 重写虚函数
void CTransferServer::_DoReadEventHandle(int connectfd)
{
	TraceLog("%d", connectfd);

  std::map<int, Connect*>::iterator it = _connectMap.find(connectfd);
	if (it != _connectMap.end()){
		Connect* connect = it->second;
		Channel* clientChannel = &connect->_clientChannel;
		Channel* serverChannel = &connect->_serverChannel;
		bool recvDecrypt = false;
		bool sendEncry = true;

    // 统一处理, 从客户端读消息, 往服务器写消息
		if (connectfd == connect->_serverChannel._fd){
			std::swap(clientChannel, serverChannel);
			std::swap(recvDecrypt, sendEncry);
		}

		Forward(clientChannel, serverChannel, recvDecrypt, sendEncry);
	}
	else{
		assert(false);
	}
}

int main()
{
	CTransferServer server("127.0.0.1", 8800);
	server.StartUp();
}
